﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using TensionCurve.BLL;
using TensionCurve.DAL;
using TensionCurve.Models;

namespace TensionCurve
{
    public partial class Form1 : Form
    {
        private IPlcService _plcService;
        private ITensionDataService _dataService;
        private DataCollectionService _collectionService;
        private bool _isInitialized = false;

        private List<float> curveDatas=new List<float>(1024);
        private List<DateTime> curveTimes=new List<DateTime>(1024);

        public Form1()
        {
            InitializeComponent();
            InitializeServices();
        }

        /// <summary>
        /// 初始化服务
        /// </summary>
        private void InitializeServices()
        {
            try
            {
                // 初始化服务
                _plcService = new MitsubishiPlcService();
                var repository = new TensionDataRepository();
                _dataService = new TensionDataService(repository);
                _collectionService = new DataCollectionService(_plcService, _dataService);

                // 订阅事件
                _collectionService.DataCollected += OnDataCollected;
                _collectionService.CollectionStarted += OnCollectionStarted;
                _collectionService.CollectionStopped += OnCollectionStopped;
                _collectionService.ErrorOccurred += OnErrorOccurred;

                UpdateStatus("服务初始化完成");
            }
            catch (Exception ex)
            {
                UpdateStatus($"服务初始化失败: {ex.Message}");
                MessageBox.Show($"服务初始化失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                // 初始化数据库
                await _dataService.InitializeAsync();
                
                // 设置时间选择器默认值
                dtpStartTime.Value = DateTime.Today;
                dtpEndTime.Value = DateTime.Now;

                _isInitialized = true;
                UpdateStatus("系统初始化完成，准备就绪");
            }
            catch (Exception ex)
            {
                UpdateStatus($"系统初始化失败: {ex.Message}");
                MessageBox.Show($"系统初始化失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// PLC连接按钮事件
        /// </summary>
        private async void btnConnect_Click(object sender, EventArgs e)
        {
            if (!_isInitialized)
            {
                MessageBox.Show("系统未初始化完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                btnConnect.Enabled = false;
                UpdateStatus("正在连接PLC...");

                string ipAddress = txtIpAddress.Text.Trim();
                if (!int.TryParse(txtPort.Text.Trim(), out int port))
                {
                    port = 6000;
                }

                bool connected = await _plcService.ConnectAsync(ipAddress, port);
                
                if (connected)
                {
                    btnConnect.Enabled = false;
                    btnDisconnect.Enabled = true;
                    btnStartCollection.Enabled = true;
                    
                    UpdateStatus($"PLC连接成功: {ipAddress}:{port}");
                    
                    // 开始监控PLC状态
                    _collectionService.StartMonitoring();
                }
            }
            catch (Exception ex)
            {
                btnConnect.Enabled = true;
                UpdateStatus($"PLC连接失败: {ex.Message}");
                MessageBox.Show($"PLC连接失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// PLC断开连接按钮事件
        /// </summary>
        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            try
            {
                _plcService.Disconnect();
                
                btnConnect.Enabled = true;
                btnDisconnect.Enabled = false;
                btnStartCollection.Enabled = false;
                btnStopCollection.Enabled = false;
                
                UpdateStatus("PLC连接已断开");
            }
            catch (Exception ex)
            {
                UpdateStatus($"断开PLC连接失败: {ex.Message}");
                MessageBox.Show($"断开PLC连接失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 手动开始采集按钮事件
        /// </summary>
        private void btnStartCollection_Click(object sender, EventArgs e)
        {
            try
            {
                _collectionService.ManualStartCollection();
            }
            catch (Exception ex)
            {
                UpdateStatus($"开始采集失败: {ex.Message}");
                MessageBox.Show($"开始采集失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 手动停止采集按钮事件
        /// </summary>
        private void btnStopCollection_Click(object sender, EventArgs e)
        {
            try
            {
                _collectionService.ManualStopCollection();
            }
            catch (Exception ex)
            {
                UpdateStatus($"停止采集失败: {ex.Message}");
                MessageBox.Show($"停止采集失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 查询按钮事件
        /// </summary>
        private async void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                btnQuery.Enabled = false;
                UpdateStatus("正在查询历史数据...");

                DateTime startTime = dtpStartTime.Value;
                DateTime endTime = dtpEndTime.Value;

                if (startTime >= endTime)
                {
                    MessageBox.Show("开始时间必须小于结束时间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                var historyData = await _dataService.QueryTensionDataByTimeRangeAsync(startTime, endTime);
                
                if (historyData.Count == 0)
                {
                    MessageBox.Show("指定时间范围内无数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    UpdateStatus($"查询完成，未找到数据 ({startTime:yyyy-MM-dd HH:mm:ss} - {endTime:yyyy-MM-dd HH:mm:ss})");
                    return;
                }

                // 显示历史数据到曲线控件
                DisplayHistoryData(historyData);
                UpdateStatus($"查询完成，共找到 {historyData.Count} 条数据");
            }
            catch (Exception ex)
            {
                UpdateStatus($"查询历史数据失败: {ex.Message}");
                MessageBox.Show($"查询历史数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnQuery.Enabled = true;
            }
        }

        /// <summary>
        /// 显示历史数据到曲线控件
        /// </summary>
        private void DisplayHistoryData(List<TensionData> historyData)
        {
            if (historyData == null || historyData.Count == 0) return;

            try
            {
                // 准备数据用于显示
                var dataPoints = historyData.OrderBy(x => x.CollectionTime).ToList();
                
                UpdateStatus($"准备显示 {dataPoints.Count} 条历史数据到曲线");
                
                // 注意：这里需要根据实际的HslCurveHistory API文档来实现数据显示
                // 当前仅记录数据准备完成的状态
                
                UpdateStatus($"历史数据准备完成，共 {dataPoints.Count} 条数据");
            }
            catch (Exception ex)
            {
                UpdateStatus($"显示历史数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 数据采集事件处理
        /// </summary>
        private void OnDataCollected(object sender, TensionData data)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<object, TensionData>(OnDataCollected), sender, data);
                return;
            }

            try
            {
                // 显示实时数据
                // 注意：这里需要根据实际的HslCurveHistory API文档来实现实时数据显示
                curveDatas.Add(data.TensionValue);
                curveTimes.Add(data.CollectionTime);
                UpdateCurve();
                UpdateStatus($"实时采集: 张力值={data.TensionValue:F2}, 时间={data.CollectionTime:HH:mm:ss.fff}");
            }
            catch (Exception ex)
            {
                UpdateStatus($"显示实时数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 采集开始事件处理
        /// </summary>
        private void OnCollectionStarted(object sender, string batchId)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<object, string>(OnCollectionStarted), sender, batchId);
                return;
            }

            lblCollectionStatus.Text = "采集状态: 正在采集";
            lblCurrentBatch.Text = $"当前批次: {batchId.Substring(0, 8)}...";
            btnStartCollection.Enabled = false;
            btnStopCollection.Enabled = true;
            
            UpdateStatus($"开始数据采集，批次ID: {batchId}");
        }

        /// <summary>
        /// 采集停止事件处理
        /// </summary>
        private void OnCollectionStopped(object sender, string batchId)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<object, string>(OnCollectionStopped), sender, batchId);
                return;
            }

            lblCollectionStatus.Text = "采集状态: 已停止";
            btnStartCollection.Enabled = true;
            btnStopCollection.Enabled = false;
            
            UpdateStatus($"数据采集已停止，批次ID: {batchId}");
        }

        /// <summary>
        /// 错误事件处理
        /// </summary>
        private void OnErrorOccurred(object sender, string errorMessage)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<object, string>(OnErrorOccurred), sender, errorMessage);
                return;
            }

            UpdateStatus($"错误: {errorMessage}");
        }

        /// <summary>
        /// 更新状态显示
        /// </summary>
        private void UpdateStatus(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>(UpdateStatus), message);
                return;
            }

            string timeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            lblStatus.Text = $"[{timeStamp}] {message}\r\n" + lblStatus.Text;
            
            // 限制状态显示的行数
            var lines = lblStatus.Text.Split('\n');
            if (lines.Length > 5)
            {
                lblStatus.Text = string.Join("\n", lines.Take(5));
            }
        }

        //更新曲线
        private void UpdateCurve()
        {
            if (curveDatas.Count > 0)
            {
                hslCurveHistory1.SetLeftCurve("张力1", curveDatas.ToArray(),Color.Blue, HslControls.CurveStyle.Curve);
                hslCurveHistory1.SetDateTimes(curveTimes.ToArray());
                hslCurveHistory1.RenderCurveUI();
            }
        }

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                _collectionService?.Dispose();
                _plcService?.Dispose();
            }
            catch (Exception ex)
            {
                // 忽略释放资源时的异常
                System.Diagnostics.Debug.WriteLine($"释放资源异常: {ex.Message}");
            }
        }
    }
}
